import { createRouter, createWebHashHistory, createWebHistory, RouteRecordRaw, useRouter } from 'vue-router';
import Layout from '@/layout/index.vue';
import useUserStore from '@/store/user'
import setting, { asyncRoutes } from './setting'
import 'vue-router';
import auth from '@/utils/auth';

// 补充 meta 类型
declare module 'vue-router' {
  interface RouteMeta {
    title: string,
    icon?: string
  }

  interface _RouteRecordBase {
    hidden?: boolean
    noShowingChildren?: boolean
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/login',
    component: () => import('@/views/login/index.vue'),
    hidden: true,
    status: true
  },
  
  {
    path: '/loginScan',
    component: () => import('@/views/loginScan/index.vue'),
    hidden: true,
    status: true
  },
  {
    path: '/success',
    component: () => import('@/views/loginScan/success.vue'),
    hidden: true,
    status: true
  },
  {
    path: '/404',
    component: () => import('@/views/404.vue'),
    hidden: true,
    status: true
  }
]

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH),
  routes
})

export const createAsyncRouter = () => {
  const userStore = useUserStore()
  const newRoutes: any[] = []
  if (userStore.name && userStore.name.manager_id === 1) {
    newRoutes.push(...asyncRoutes)
  } else {
    for (const item of asyncRoutes) {
      item.children = item.children.filter(child => {
        return child.path === '/home' || auth.check(child.isPermiss)
      })
      if (item.children.length > 0) {
        newRoutes.push(item)
      }
    }
  }
  for (const item of newRoutes) {
    router.addRoute(item)
  }
  router.addRoute({ name: '404', path: '/:catchAll(.*)', redirect: '/404', hidden: true })
  return router
}

export const resetRouter = () => {
  let remRoutes = router.getRoutes()
  remRoutes.forEach(route => {
    const { name } = route
    if (name) router.removeRoute(name)
  })
  for (const item of routes) {
    router.addRoute(item)
  }
}

export default router

